I'm trying to verify some inputs inside a form with javascript before send it with POST to a PHP controller.
the JS code looks like this, verifyng cellphone number, email, and password:
function registerUser(){
// Validate Email
event.preventDefault();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate()
{
var email = document.getElementById("emailReg").val();
if (validateEmail(email))
{
var celular = document.getElementById("cellReg").val();
if(celular.lenght >= 10 && /[0-9]/.test(celular))
{
var pass = document.getElementById("passwordReg").val();
if(pass.length >= 6 && /[a-zA-Z]/.test(pass))
{
alert("correct data");
document.forms['registerForm'].submit();
}
else
{
// document.forms['registroForm'].submit();
event.preventDefault();
alert("password need to has at leas 6 characters and one uppercase");
}
}
else
{
event.preventDefault();
alert("Phone number must not have letters");
}
}
else
{
event.preventDefault();
alert("Incorrect e-mail");
}
return false;
}
}
this is the Form:
<form class="form row" method="POST" name="registerForm">
<input type="email" class="form-reg" name="emailReg" id="emailReg" placeholder="example#email.com" style="width:140px;" required>
<input type="text" class="formulario-registro" name="cellReg" id="cellReg" placeholder="cellphone number" style="width: 130px;" required>
<input type="password" class="formulario-registro" name="passwordRegistro" id="passwordRegistro" placeholder="contraseña" style="width: 140px;" required>
<button type="button" class="btn btn-round btn-qubit title" onclick="registroUser();">Registrarme</button>
</form>
I have to check the lenght and if the password has at least one uppercase, with the cellphone number if it has only numbers and at least 10 characters, if i write the type="number" property in the input tag it will appear with up and down arrows which i don't want to show, i could put the conditions in my php butin that way the form will get erased when i submit it and that's what i don't want to do.
Use the following CSS for this issue
if i write the type="number" property in the input tag it will appear with up and down arrows which i don't want to show
/* Hide Up and Down arrows. */
input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
I apply function on submit for the form... when it's submitted the JS code below verify if the conditions are true and then it is sended to the php controller.
$(document).ready(function(){
$(".registerForm").on('submit', function(event)
{
var validate = validate();
if(validate === "success")
{
console.log("success");
document.forms['registerForm'].submit();
}
else{
event.preventDefault();
}
});
// validate password //
function validate()
{
var email = $("#emailRegister").val();
if (validateEmail(email))
{
var cell = $("#cellRegister").val();
if(cell.length === 10)
{
var pass = $("#passwordRegister").val();
if(pass.length >= 6 && /[A-Z]/.test(pass))
{
console.log("correct data");
return "success";
}
else
{
alert("password must have a lenght of 6 digits and at least one capital letter");
return "false";
}
}
else
{
alert("cellphone must be minimum a 10 digits number");
return "false";
}
}
else
{
alert("incorrect e/mail adress");
return "false";
}
}
// Validate Email
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
});
Related
I have written this code but it doesn't work. I click the button check input:email and check the text.
function EpostaKontrol(eposta) {
if (eposta.indexof("#") != -1) {
var dizi = eposta.split("#");
if (!(alfaNummerikKonrol(dizi[0]))) {
if (domain.indexof(".") != -1) {
var domain = dizi[1].split(".");
if (dizi[0].length >= 3 && dizi[1].length >= 5 && domain[1].length >= 2)
alert("Email Format Wrong");
}
}
}
}
Please run the code snippet below:
function validateEmail(email) {
return /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/.test( email );
}
$(document).on( 'click', '#validate', function(){
var email = $('#email').val();
if (validateEmail(email))
console.log('This is a valid email!');
else
console.log('This is NOT a valid email!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email"><input type="button" value="Validate if email" id="validate">
you can also achieve this by below code
mozilla Ref :
var email = document.getElementById("mail");
//email.setCustomValidity("I expect an e-mail, darling!");
email.addEventListener("input", function (event) {
checkEmail(email)
});
function checkEmail(email){
if (email.validity.patternMismatch) {
email.setCustomValidity("I expect an e-mail");
console.log("Invalid")
} else {
email.setCustomValidity("");
console.log("valid")
}
}
<h3>Show an e-mail field (allows only one email address):</h3>
<form action="/action_page.php">
E-mail: <input id='mail' type="email" name="emailaddress"pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
required>
<input type="submit" onclick="checkEmail(email)" >
</form>
here is my script
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
enter.disabled = true;
} else if (user_pass == user_pass2 ){
enter.disabled = false;
} else {
enter.disabled = true;
alert("Your password doesn't same");
}
});
this my html
Password : <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
i am really new in Javascript and jQuery, and this is my first using jquery. i need to make a disabled button if the password doesn't match but, after i put the same password the button is still disabled.
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
//var enter = $("#enter").val();
if (user_pass.length == 0) {
alert("please fill password first");
$("#enter").prop('disabled',true)//use prop()
} else if (user_pass == user_pass2) {
$("#enter").prop('disabled',false)//use prop()
} else {
$("#enter").prop('disabled',true)//use prop()
alert("Your password doesn't same");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Password :
<input type="password" name="user[user_pass]" id="reg_pass" required="required">Confirm password
<input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
Use .prop()
You need to set disable attribute like this in jquery $("#enter").attr('disabled',true);
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").attr('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").attr('disabled',false);
} else {
$("#enter").attr('disabled',true);
alert("Your password doesn't same");
}
The .prop( propertyName, value ) allow you set one or more properties for the set of matched elements.
JS
$(function() {
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var confirm_user_pass = $("#reg_confirm_pass").val();
var enter = $("#enter");
if (user_pass.length == 0) {
alert("please fill password first");
enter.prop('disabled', true)
}
else if (user_pass == confirm_user_pass) {
enter.prop('disabled', false)
}
else {
enter.prop('disabled', true)
alert("Your password doesn't match");
}
});
});
HTML
Password: <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password: <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
I believe the other answers are right on target. I set up a simple 'jsfiddle' using jquery and its .prop() method to better illustrate here.
NOTE: I would probably bind to another event to make it fire when changes are made to either input element.
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").prop('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").prop('disabled',false);
} else {
$("#enter").prop('disabled',true);
alert("Your password doesn't same");
}
});
Actually blur will not enable the button instantly, keyup eventhandler does the best job. Here's the below code.
$("#reg_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
$("#reg_confirm_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
Here it responds to the changes in either of the text boxes instantly.
Check it here.
Any better solution than this, please let me know. Thank you.
How to validate Email or Phone Number Using Single Input?
I like to have input value xyz#gmail.com OR 1234567890 anything else alert "Invalid Email or phone number"
Like Facebook Sign Up form
<form>
<input type="text" placeholder="Email or mobile number" />
<button type="submit" >Sign Up</button>
</form>
Thanks!!
I Did using two regular expressions like
function validateEmail() {
var email = document.getElementById('txtEmail');
var mailFormat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|([0-9]{10})+$/;
if (email.value == "") {
alert( " Please enter your Email or Phone Number ");
}
else if (!mailFormat.test(email.value)) {
alert( " Email Address / Phone number is not valid, Please provide a valid Email or phone number ");
return false;
}
else {
alert(" Success ");
}
}
I'd probably test it with two regexes. First check for one (e.g. is it a valid email), then if that fails, check it with the other (e.g. is it a valid phone number). If neither, show a validation message saying that the value is invalid. I won't supply regex examples here as there are dozens of those around the internet and each has pros and cons - no sense starting a flame war over the best regex for email or phone, but the code would look like the following:
function validateEmailPhoneInput(field)
{
if (emailRegex.test(field.value))
{
//it's an email address
}
else if (phoneRegex.test(field.value))
{
//it's a phone number
}
else
{
//display your message or highlight your field or whatever.
field.classList.add('invalid');
}
}
Try this it's working:
<script>
$(document).ready(function () {
$("#cuntryCode").hide();
$("#useridInput").on('input', function () {
var len = $("#useridInput").val().length;
if (len >= 2) {
var VAL = this.value;
var intRegex = /^[1-9][0-9]*([.][0-9]{2}|)$/;
if (!intRegex.test(VAL)) {
$('#error-caption').html('Invalid email. Please check spelling.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").hide();
} else {
if(len < 10){
$('#error-caption').html('Invalid mobile number. Please try again.');
$('#error-caption').css('color', 'red');
$("#cuntryCode").show();
}else{
$('#error-caption').html('Invalid mobile number. length must be 10 digit.');
$('#error-caption').css('color', 'red');
}
}
}else{
$("#cuntryCode").hide();
$('#error-caption').html('');
}
});
});
</script>
<form class="push--top-small forward" method="POST" data-reactid="15">
<h4 id="input-title" data-reactid="16">Welcome back
</h4>
<label class="label" id="input-label" for="useridInput" data-reactid="17">Sign in with your email address or mobile number.
</label>
<div style="margin-bottom:24px;" data-reactid="18">
<div >
<div id="cuntryCode" class="_style_4kEO6r" style="float: left; height: 44px; line-height: 44px;">
<div tabindex="0" > +241
</div>
</div>
<div style="display:flex;">
<input id="useridInput" autocorrect="off" autocapitalize="off" name="textInputValue" class="text-input" placeholder="Email or mobile number" aria-required="true" aria-invalid="false" aria-describedby="error-caption input-title">
</div>
</div>
<div id="error-caption">
</div>
</div>
<button class="btn btn--arrow btn--full" data-reactid="24">
<span class="push-small--right" data-reactid="25">Next
</span>
</button>
</form>
$("#volunteer_submit").click(function myfunction() {
function email_number_check() {
var email_number = $("input[name=email_mobile]").val();
if (email_number == "") {
alert("Fill in the Required Fields field cannot be empty");
}
else if (isNaN(email_number) == true) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email_number) == false) {
alert('Invalid Email Address');
}
else {
$("#contact-form").submit();
}
}
else if (isNaN(email_number) == false) {
var reg_mobile = /^(\+\d{1,3}[- ]?)?\d{10}$/;
if (reg_mobile.test(email_number) == false) {
alert('Invalid mobile');
}
else {
$("#contact-form").submit();
}
}
}
email_number_check();
});
This code is worked for me.
var a=document.getElementById('txtEmail').value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(a=="")
{
alert('Please enter value');
return false;
}
else if(isNaN(a))
{
if(!(a.match(mailformat)))
{
alert('Please enter email address/phno valid');
return false;
}
}
else
{
if(a.length()!=10)
{
alert('Please enter valid phno');
return false;
}
}
I want to keep viewers from entering words like "fssadf", and force them to enter a valid email which must contain the "#" in the middle and "." to prevent spam and injection.
I also want the form to display an error message that says "change the email field to the correct email"
I use js_function.js which contain this:
function validEmail()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
but it does not prevent the viewer from sending me "sfdasfd" instead of a valid email.
What can I do to achieve the above?
check out the files below:
http://www.mediafire.com/?kx5bvttc0s2fbrs
thanks,
rami
Though I didn't see any error on my program what you provided but still you may
use
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
instead of this
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
I think that will help. I provided the total Javascript code what worked properly for me.
function validEmail()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
Use this
or you may use this too in other way
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate(this.value)" />
//Other Codes
</form>
And Javascript
<script>
function validate(email)
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
OR
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
And the last solution will be quiet easier to apply I think.
Error Message on Page instead of Popup
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
<span id="errormessage"></span>
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
document.getElementById('errormessage').innerHTML= 'fill your email';
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
document.getElementById('errormessage').innerHTML= '';
return true;
}
}
</script>
try with this
$(document).ready(function() {
$('#btn-submit').click(function() {
$(".error").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#UserEmail").val();
if(emailaddressVal == '') {
$("#UserEmail").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
});
Duplicate of this question:
Validate email address in JavaScript?
There is some valuable discussion in the comments about edge cases that SHOULD NOT be ignored.
Did you try to Google this one before you asked? IT is a /very/ common question.
If you're after a pure HTML5 solution using jQuery.... Here's a live demo
HTML
<form id="form">
Email <input name="field1" required="required" type="email" /> <br />
<div id="error"></div>
<input required="required" name="submit" type="submit" />
</form>
Code
$(document).ready(function() {
var validCheckInput = function() {
if ($(this)[0].checkValidity()) {
$(this).removeClass("error");
$("#error").empty();
} else {
$(this).addClass("error");
$("#error").text("change the email field to the correct email");
}
if ($("#form")[0].checkValidity()) {
$("#form input[type='submit']").removeAttr("disabled");
} else {
$("#form input[type='submit']").attr("disabled", "disabled");
}
};s
var binds = function(validCheck) {
$(this).change(validCheck);
$(this).focus(validCheck);
$(this).keyup(validCheck);
validCheck.call($(this));
}
$("#form input").each(function() {binds.call(this, validCheckInput)});
});
CSS
.error {
border: 2px solid red;
}
First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.