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.
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";
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With