How to check input field pattern validation on if else condition javascript? to show message div for valid and Invalid on button submit on type for pattern validation?
function myFunction(element) {
if (document.getElementById("smsno").value.length == 0) {
document.getElementById("sms_ntvalidate").style.display = "block";
document.getElementById("sms_validate").style.display = "none";
} else {
document.getElementById("sms_validate").style.display = "block";
document.getElementById("sms_ntvalidate").style.display = "none";
}
}
<div class="form-row">
<div class="form-group col-md-6 smsForm">
<label for="contact1">SMS No.<span style="color:#ff0000">*</span></label>
<input type="tel" class="form-control" name="smsno" id="smsno"
placeholder="SMS No." pattern="^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$"
required onkeyup="myFunction(this)" />
<div class="custm-valid" id="sms_validate" style="display:none;">Valid.</div>
<div class="custm-invalid" id="sms_ntvalidate" style="display:none;">Please enter valid contact no.</div>
</div>
<div class="form-group col-md-6 whatsappForm">
<label for="contact2">WhatsApp No.<span style="color:#ff0000">*</span></label>
<input type="text" class="form-control" name="whtspno" id="whtspno"
placeholder="WhatsApp No." pattern="^(00|\+)[1-9]{1}([0-9][\s]*){9,16}$"
required />
<div class="custm-valid" id="whts_validate"style="display:none;">Valid.</div>
<div class="custm-invalid" id="whts_ntvalidate" style="display:none;">Please enter valid contact no.</div>
</div>
</div>
Your pattern is number you can use custom js for thise validation like
document.getElementById("smsno").value.forEach((value)=>{ if(value >== 0 && value <== 9) { // Condition} else { //Wrong Pattern condition } );
The forEach checkes the every single element on input
Related
I am trying to validate a form. I am successful on that, but if the alert kicks in, the page refresh and since i am using a pop up, this one closes and i have to open it again. I need to prevent that in the case of a miss click.
Here are the code:
HTML
<div class="row">
<form action="" method="" id="formBoard" name="formOfBoard">
<div class="col-75">
<label for="bname">Name of the Board: </label><br>
<input type="text" id="boardname" name="boardname">
</div>
<div class="row">
<div class="col-75">
<label for="ipadd">IP Address:</label><br>
<input type="text" name="ipadd" id="ipaddress">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="portnum">Port:</label><br>
<input type="text" name="portnum" id="portnum">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="imgadd">Upload image:</label><br>
<img src="node_modules/#tabler/icons/icons-png/file-upload.png" alt="Insert image" class="insrtimg" name="imageboard" id="insertimage">
</div>
</div>
<div class="row">
<div class="col-80">
<div>
<div class="btnfrm" style="background-color: #F30D0DBF; color:antiquewhite" onclick="closeForm()">Discard</div>
<input type="submit" class="btnfrm" style="background-color: rgb(67, 221, 67);" value="Save" onclick="validateIndexForm()">
</div>
</div>
</div>
</form>
</div>
</form>
</div>
JavaScript
function validateIndexForm(){
let x = document.getElementById("boardname").value;
let y = document.getElementById("ipaddress").value;
let z = document.getElementById("portnum").value;
let w = document.getElementById("insertimage").value;
let ipfrmt = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;;
if(x == ""){
alert("Please insert the boards name");
return false;
}
if(!y.match(ipfrmt)){
alert("Please insert a valid IP address");
return false;
}
if(z != isNaN() && !(z > 0)){
alert("Please insert the correct port");
return false;
}
return x, y, z;
}
The likely reason for the reload may be from the form action that is returning the default values into the URL, meaning it is causing new navigation (this can be seen in the dev console, such as chrome, by turning this on via the dev tool preferences.
I have tested this only with the HTML/JavaScript so not sure what other parts of the application are doing but hopefully this helps.
Change the button onclick to the form onsubmit action
passing through the event to the function
prevent default when an error occurs
<div class="row">
<form action="" method="" id="formBoard" name="formOfBoard" onsubmit="validateIndexForm(event)">
<div class="col-75">
<label for="bname">Name of the Board: </label><br>
<input type="text" id="boardname" name="boardname">
</div>
<div class="row">
<div class="col-75">
<label for="ipadd">IP Address:</label><br>
<input type="text" name="ipadd" id="ipaddress">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="portnum">Port:</label><br>
<input type="text" name="portnum" id="portnum">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="imgadd">Upload image:</label><br>
<img src="node_modules/#tabler/icons/icons-png/file-upload.png" alt="Insert image" class="insrtimg" name="imageboard" id="insertimage">
</div>
</div>
<div class="row">
<div class="col-80">
<div>
<div class="btnfrm" style="background-color: #F30D0DBF; color:antiquewhite" onclick="closeForm()">Discard</div>
<input type="submit" class="btnfrm" style="background-color: rgb(67, 221, 67);" value="Save" >
</div>
</div>
</div>
</form>
</div>
</form>
</div>
function validateIndexForm(event){
let x = document.getElementById("boardname").value;
let y = document.getElementById("ipaddress").value;
let z = document.getElementById("portnum").value;
let w = document.getElementById("insertimage").value;
let ipfrmt = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;;
if(x == ""){
event.preventDefault();
alert("Please insert the boards name");
return false;
}
if(!y.match(ipfrmt)){
event.preventDefault();
alert("Please insert a valid IP address");
return false;
}
if(z != isNaN() && !(z > 0)){
event.preventDefault();
alert("Please insert the correct port");
return false;
}
return x, y, z;
}
Note: to make further improvements to the lines of code that are repeated (prevent default) the function could be broken out into a validation function that returns true or false based on the inputs.
I created a html form and a function validateForm() to validate the form fields. However the function is only reporting issues with wrong email input, and its not validating the other fields in the form. Can you check my code to see if i have any errors.
Thanks
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Support Center</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/layout.css" type="text/css">
<link rel="stylesheet" href="styles/Form.css" type="text/css">
<script type="text/javascript" src="Form.js"></script>
</head>
<body>
<div class="wrapper row1">
<header id="header" class="clear">
<div id="hgroup">
<h1>Support Center</h1>
<h2>Welcome to our website</h2>
</div>
<nav>
<ul>
<li>Home</li>
<li>Our Staff</li>
<li>Location</li>
<li>Help</li>
<li class="last"></li>
</ul>
</nav>
</header>
</div>
</body>
<!-- content -->
<body>
<h1>Help is here!</h1>
<form>
<h1>Should you need assistance, please do not hesitate to contact us:</h1>
<div class="contentform">
<div id="sendmessage"> Your form has been sent successfully. Thank you. </div>
<div class="leftcontact">
<div class="form-group">
<p>Surname<span>*</span></p>
<span class="icon-case"><i class="fa fa-male"></i></span>
<input type="text" name="lastName" id="lastName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>First Name <span>*</span></p>
<span class="icon-case"><i class="fa fa-user"></i></span>
<input type="text" name="firstName" id="firstName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>E-mail <span>*</span></p>
<span class="icon-case"><i class="fa fa-envelope-o"></i></span>
<input type="email" name="emailAddress" id="emailAddress"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Office <span>*</span></p>
<span class="icon-case"><i class="fa fa-location-arrow"></i></span>
<input type="text" name="office" id="office"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Desk <span>*</span></p>
<span class="icon-case"><i class="fa fa-map-marker"></i></span>
<input type="text" name="deskNumber" id="deskNumber"/>
<div class="validation"></div>
</div>
</div>
<div class="rightcontact">
<div class="form-group">
<p>Phone number <span>*</span></p>
<span class="icon-case"><i class="fa fa-phone"></i></span>
<input type="text" name="mobilePhone" id="mobilePhone"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Job Number <span>*</span></p>
<span class="icon-case"><i class="fa fa-building-o"></i></span>
<input type="text" name="jobNumber" id="jobNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Computer <span>*</span></p>
<span class="icon-case"><i class="fa fa-info"></i></span>
<input type="text" name="computerNumber" id="computerNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comment-o"></i></span>
<select name="Problem">
<option value="New User">New User</option>
<option value="Delete User">Delete User</option>
<option value="Lost File">Lost File</option>
<option value="New Software Installation">New Software Installation</option>
<option value="Virus Checking">Virus Checking</option>
</select>
<div class="validation"></div>
</div>
<div class="form-group">
<p>A little about your problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comments-o"></i></span>
<textarea name="message" rows="14"></textarea>
<div class="validation"></div>
</div>
</div>
</div>
<button type="submit" class="bouton-contact">Send</button>
</form>
</body>
</html>
</body>
</html>
Code
function validateForm() {
var letters = "[A-Za-z]+$";
var numbers = "^[0-9]+$";
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var jobNumber = document.getElementById("jobNumber").value;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var mobilePhone = document.getElementById("mobilePhone").value;
var emailAddress = document.getElementById("emailAddress").value;
var officeNumber = document.getElementById("office").value;
var deskNumber = document.getElementById("deskNumber").value;
var computerNumber = document.getElementById("computerNumber").value;
if(jobNumber != "" && firstName != "" && lastName != "" && mobilePhone != "" && emailAddress != "" && officeNumber != "" && deskNumber != "" && computerNumber != "") {
if(jobNumber.length == 5 && jobNumber.match(numbers)) {
if(firstName.match(letters) && lastName.match(letters)) {
if(mobilePhone.length == 10 && mobilePhone.match(numbers)) {
if(emailAddress.match(emailReg)) {
alert("Form submitted!");
return true;
}
else {
alert("Please enter a valid email");
return false;
}
}
else {
alert("Please enter a valid mobile number");
return false;
}
}
else {
alert("Please enter a valid first name and last name");
return false;
}
}
else {
alert("Please enter a valid job number");
return false;
}
}
else {
alert("Please enter in all fields");
return false;
}
}
Edit: I just noticed you're using a class contentform and I thought it was an id. I would also add an id to your form to be able to retrieve all form data with one DOM traversal instead of several.
Also, the reason the email is the only one working is because the browser is validating the email without using your JS.
First I would ditch all the variables declared and replace it with the form object.
var formObject = document.getElementById('contentform');
Then you could check whatever child elements that are required. I would also remove the nesting of your if statements, and instead of alerting an error and returning false, add the error to an array to store each one, then return after all items are validated.
var errorList = [];
var isValid = true;
if(formObject.jobNumber == "") {
errorList.push('Please enter a valid job number');
isValid = false;
}
Then rinse and repeat for each element required. After that, just return the list and status (isValid).
// this should be on its own at the bottom of your function right before you return
if (!isValid) {
alert(errorList);
// I would add some formatting or preferably display in the form view.
}
return isValid;
html file
// add the event handler here
<button type="submit" onclick="validateForm()" class="bouton-contact">Send</button>
Also, these
if (!isValid) {
alert(errorList);
}
should be removed from each if statement and placed at the bottom after all have been checked.
Here you validate your email address: First pass the id to javascript by post method then the function validation() will works.
//html
<div>
<input type="text" name="email" id="email" class="" data-wow-delay=".5s" value="" placeholder="Email..." />
</div>
<span id="emailerror" style="display:none; color:#F00">Enter valid email id*</span>
<input type="submit" onClick="return validation();" class="wow fadeInUp" value="Send" />
//javascript
function validation()
{
var email = document.getElementById('email').value;
if(email == '' || !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)))
{
document.getElementById('emailerror').style.display = 'inline';
var error=1;
}
else
{
document.getElementById('emailerror').style.display = 'none';
}
if(error == 1)
{
return false;
}
else
{
return true;
}
}
now your email validation works fine, thanks
This question already has answers here:
checking if a number is float in PHP
(5 answers)
Closed 7 years ago.
Hi i'm trying to validate user input on a form using PHP.
I have managed to validate text, numeric and year input but can't get price to work.
I create error variables at the top of my code:
$titleErr = ""; $developerErr = ""; $releaseErr = ""; $stockErr = ""; $priceErr = "";
I then validate the input and assign a message to the variable if needs be:
if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
$titleErr = "Invalid input, only letters and white space allowed.";
} else if (!preg_match("/^[a-zA-Z ]*$/",$developer)){
$developerErr = "Invalid input, only letters and white space allowed.";
} else if ($release<1990 || $release>2020){
$releaseErr = "Invalid input, enter a year between 1990 & 2020.";
} else if (!is_numeric($stock)){
$stockErr = "Invalid input, only numbers allowed.";
} else if (!is_float($price)){
$priceErr = "Invalid input, only doubles allowed.";
}
The first 4 statements validate input perfectly. However the last one that is checking if the input is a float (for price e.g. 10.99) seems to return the error message when I enter correct input.
This is my form:
<form class ="form-horizontal" role="form" id="add" name="add" action="?" method="post">
<div class="form-group">
<label class="control-label col-sm-2">Title</label> <div class="col-sm-10"><input class="form-control" id="addFormTitle" name="title" type="text"> <span class="error"><?php echo $titleErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Developer</label> <div class="col-sm-10"><input class="form-control" id="addFormDeveloper" name="developer" type="text"> <span class="error"><?php echo $developerErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Release (Year Format/YYYY)</label> <div class="col-sm-10"><input class="form-control" id="addFormRelease" name="release" type="text"> <span class="error"><?php echo $releaseErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Stock</label> <div class="col-sm-10"><input class="form-control" id="addFormStock" name="stock" type="text"> <span class="error"><?php echo $stockErr;?></span></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Price (£)</label> <div class="col-sm-10"><input class="form-control" id="addFormPrice" name="price" type="text"> <span class="error"><?php echo $priceErr;?></span></div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="addSubmit" value="Add product">Submit</button>
</div>
</div>
</form>
You can use floatval function to get the float value of a variable and then check whether it's a float value or not, like this:
if(is_float(floatval($price))){
echo "float value";
}else{
echo "not a float value";
}
Edited:
In your code you can do something like this:
if (!preg_match("/^[a-zA-Z ]*$/",$title)) {
$titleErr = "Invalid input, only letters and white space allowed.";
} else if (!preg_match("/^[a-zA-Z ]*$/",$developer)){
$developerErr = "Invalid input, only letters and white space allowed.";
} else if ($release<1990 || $release>2020){
$releaseErr = "Invalid input, enter a year between 1990 & 2020.";
} else if (!is_numeric($stock)){
$stockErr = "Invalid input, only numbers allowed.";
} else if (!is_float(floatval($price))){
$priceErr = "Invalid input, only doubles allowed.";
}
I do need to create a form. In that form I need to enable form element one by one. That mean, If an user entered valid data to first element then I want to autofocus next element and so on.
NOTE: When page is load I want to keep all the elements disable except first element.
This is HTML of my form.
<form role="form" class="banner" method="post" action="">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="name" placeholder="Your Name" class="form-control first-name sequence" autocomplete="off" required>
<label for="name" class="glyphicon glyphicon-user" data-toggle="tooltip" data-placement="left" title="Enter Your Name"></label>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="email" name="email" placeholder="Your Email" class="form-control email_address sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-envelope" rel="tooltip" title="Enter Your Email"></label>
<span class="email-error"></span>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="phone" placeholder="Your Phone Number Eg: xx-xxx-xxx" class="form-control phone-number sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-phone" rel="tooltip" title="Enter Your Phone Number"></label>
</div>
</div>
<div class="element-left">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-date" placeholder="Pick Up Date" class="form-control datepicker sequence" autocomplete="off">
<label for="date" class="glyphicon glyphicon-calendar" rel="tooltip" title="Prefered Charter Date"></label>
</div>
</div>
</div>
<div class="element-right">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-time" placeholder="Pick Up Time" class="form-control timepicker sequence" autocomplete="off">
<label for="time" class="glyphicon glyphicon-time" rel="tooltip" title="Time of Charter"></label>
</div>
</div>
</div>
<p class="form-actions">
<button type="submit" name="submit" class="btn btn-default btn-block">
<span class="btn-orange-inner">Send</span>
</button>
</p>
</form>
This is how I tried it in jQuery:
// form validation
function fakeValidator(event) {
var flag = false;
var $element = $(event.target);
var values = $element.val();
if (values.length >= 3) {
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
flag =true;
} else {
flag =false;
}
if(flag){
//alert('hi');
$element.addClass('valid');
enableNextElement(event);
} else{
alert('hi el');
$element.removeClass('valid');
//$element.addAttr('disabled');
}
}
function validemail(value){
var emailReg ="/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/";
}
function enableNextElement(event) {
var $element = $(event.target);
if ($element.hasClass('valid')) {
$element.closest('.form-group')
.next('.form-group')
.find('.sequence')
.removeAttr('disabled');
}
}
$('.sequence').on('blur keyup', fakeValidator);
But my problem is, if I entered an invalid email next element is enabling. But I want to enable next element if its a valid email in email field.
Can anybody tell me what is wrong with this?
Thank you.
2 things:
You should return true or false from your email validation function i.e. validemail
Your regex is stored as string, and hence you cannot apply test function on it. Remove wrapping it in " "
Above mentioned changes will give you desired result.
function validemail(value){
var emailReg =/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; //regex
return emailReg.test(value); //use test which returns true or false
}
UPDATE
DEMO
It will still enable the phonenumber because you have validation written in such a way.
Your Validation:
if (values.length >= 3) {
//this is ok for name
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true;
}else{
flag =false;//even though flag is false here
}
}
flag =true; //when it comes to this line it again makes it to true
//and for email along with length>3, valid email address has also to be validated
} else {
flag =false;
}
My workaround
if (values.length >= 3) {
flag =true; //set this first
if($element.hasClass('email_address')) {//then perform other validations
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
} else {
flag =false;
}
I have a div and it contains three input text boxes(oldpassword,newpassword,confirmpassword).
<div class="searchContainer" id="chngpassword">
<div class="tableContent">
<div class="leftContent">
<div>Old Password<span class="redCLR">*</span></div>
<div>New Password<span class="redCLR">*</span></div>
<div>Confirm Password<span class="redCLR">*</span></div>
</div>
<div class="rightContent">
<div><input type="password" name="OldPassword" id="OldPassword" /></div>
<div><input type="password" name="NewPassword" id="NewPassword" /></div>
<div><input type="password" name="ConfirmPassword" id="ConfirmPassword" /></div>
</div>
</div>
<div class="searchButton" style="margin:10px 0 0 0">
<button id="btnSave">SAVE</button>
</div>
</div>
Now i have to validate the page in jquery for following scenarios:
1.Old password should not be blank.
2.New password should not be blank.
3.confirm password should not be blank.
4.old and confirm password should be same.
5.new password length should be 8-16 characters,atleast 1 special character,atleast 1 upper case,atleast 1 numericvalue.
Here is a quick solution that I think is what you are looking for . . .
function validatePassword(){
var old_pass = $('#OldPassword').val();
var new_pass = $('#NewPassword').val();
var conf_pass = $('#ConfirmPassword').val();
if(old_pass === ""){
alert('Old password should not be blank.');
}
else if(new_pass === ""){
alert('New password should not be blank.');
}
else if(conf_pass === ""){
alert('Confirm password should not be blank');
}
else if(!new_pass.match(/(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{8,16}$/))
alert('New password length should be 8-16 characters,atleast 1 special character,atleast 1 upper case,atleast 1 numericvalue');
}
else if(new_pass !== conf_pass){
alert('New and confirm password should be same');
}
return false
}
This should do it. I have it on JSFiddle if you want to see it working