jcadima
3/31/2017 - 5:03 PM

Simple validation with sweetAlert

Simple validation with sweetAlert



HTML:

<input id="process" type="submit" value="Request" class="btn btn-default submit" onclick="return validateForm()">





<script>
  

function validateForm() {
	console.log("VALIDATE FORM CLICKED") ;
	var first_name = document.forms["quote-cal"]["first_name"].value;
	var last_name  = document.forms["quote-cal"]["last_name"].value;
    var zip_from   = document.forms["quote-cal"]["shipfrom_zip"].value;
	var zip_to     = document.forms["quote-cal"]["shipto_zip"].value;
	var phone      = document.forms["quote-cal"]["phone"].value;
	var email      = document.forms["quote-cal"]["email"].value;
	// var pallets    = document.forms["quote-cal"]["pallets"].value;

	if ( !first_name.length ) {
		swal("Enter your first name", "" , "warning") ;
		document.getElementById("first_name").focus();
		return false;
	}

	if ( !last_name.length ) {
		swal("Enter your last name", "" , "warning") ;
		document.getElementById("last_name").focus();
		return false;
	}

    if (phone == null || phone == "" || validatePhone(phone) == false ) {
        swal("Phone number must be 10 digits XXX-XXX-XXXX", "" , "warning");
        document.getElementById("phone").focus();
        return false;
    }	


    if (email == null || email == "" || validateEmail(email) == false ) {
        swal("Please Enter a valid Email Address", "" , "warning");
        document.getElementById("email").focus();
        return false;
    }

    if ( validateZip(zip_from) == false ) {
        swal("Zip Code must be 5 digits only", "" , "warning");
        document.getElementById("shipfrom_zip").focus();
        return false;
    }

    if ( validateZip(zip_to) == false ) {
        swal("Zip Code must be 5 digits only", "" , "warning");
        document.getElementById("shipto_zip").focus();
        return false;
    }	


	
}


// Helper functions

function validateZip(zipcode) {
    var re = /^\d{5}$/;
    return re.test(zipcode);
}

function validatePhone(phone) {
    var re = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
    return re.test(phone);
}

function validateEmail(email) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(email);
}  
  
  
</script>