Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating username or email in the same text field

I want to validate the <input> element of a form to check for username or email. The validation should be done for the same textbox

<input id="text1" type="text" placeholder="Enter username or email">

it would be easier if done with pattern attribute in the input tag itself. Because I want to program the validation message using jscript.

like image 999
Abhay Jatin Doshi Avatar asked May 13 '26 23:05

Abhay Jatin Doshi


1 Answers

function validate(field) {
    // var field = document.getElementById('text1').value;

    // CHeck if email
    if (/\@/.test(field)) {
        // Validate email address
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(field)) {
            return (true)
        }
        console.log("You have entered an invalid email address!");
        return (false)
    } else {
        // Validate username
        var error = "";
        var stripped = field.replace(/[\(\)\.\-\ ]/g, '');

        if (stripped == "") {
            alert("You didn't enter a phone number.");
            error = "You didn't enter a phone number.";
        } else if (isNaN(parseInt(stripped))) {
            phone = "";
            error = "The phone number contains illegal characters.";
            alert("illegal characters.");
        } else if (!(stripped.length == 10)) {
            alert("wrong length");
            phone = "";
            error = "The phone number is the wrong length. Make sure you included an area code.\n";
        }
    }
}
like image 165
Pushpender Singh Avatar answered May 15 '26 17:05

Pushpender Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!