I have written a function in javascript to chek whether both fields are same or not:
javascript code:
function validate();{
var x= getElementByName("password");
var y= getElementByName("retype_password");
if(x==y) return;
else alert("password not same");
HTML code: HOW CAN I CALL THE ABOVE WRITTEN FUNCTION IN THE HTML CODE
password : <input type= "password" name="password"> <br><br>
retype password : <input type="password" name="retype_password" > <br><br>
thanks in advance
password : <input type= "password" id="password" onblur="validate()"> <br><br>
retype password : <input type="password" id="retype_password" onblur="validate()"> <br><br>
<script>
function validate() {
var x= document.getElementById("password");
var y= document.getElementById("retype_password");
if(x.value==y.value) return;
else alert("password not same");
}
</script>
Please be careful with method names in JavaScript. The correct method for picking the element by name is document.getElementsByName which returns a NodeList. So in order to get the first field with the required name you should treat the result as array:
function validate() {
var x = document.getElementsByName('password')[0].value,
y = document.getElementsByName('retype_password')[0].value;
if (x === y) {
return true;
}
alert('password not same');
return false;
}
To make the solution work correctly you have to bind the validation function as a <form> submit event (as an example):
var form = document.getElementById('myform');
form.addEventListener('submit', function() {
return validate();
}, false);
Or shorter as:
document.getElementById('myform').addEventListener('submit', validate, false);
If you don't have a form and use some button-like elements, you may bind a click event, e.g.:
var mybutton = document.getElementById('mybutton');
mybutton.addEventListener('click', function() {
if ( validate() ) {
// do AJAX request or whatever...
}
}, false);
Their are many ways to call this function.
You can add a new button :
<input type = 'button' value = 'validate' onclick = 'validate()' />
Or call the function when the focus on the text field is out :
<input type="password" name="retype_password" onblur = 'validate()' > <br><br>
Their are other ways to do (onkeydown, onchange...) check JS events to learn more : http://www.w3schools.com/jsref/dom_obj_event.asp
Right code from #VisioN :
function validate(event) {
var x = document.getElementsByName('password')[0].value,
y = document.getElementsByName('retype_password')[0].value;
if (x === y) {
return true;
} else {
alert('password not same');
event.preventDefault();
return false;
}
}
Add a onclick="validate(event);" attribute on the submit button.
(if validate return false, prevent the event from bubbling with event.preventDefault();).
EDIT
Maybe it is better tyo bind it to onSubmit event.
<form onsubmit="validate(event)">
Apolo
You have to use getElementById instead of getElementByName
Javascript:
function validate() {
var x = getElementById("password").value;
var y = getElementById("retype_password").value;
if(x==y) {
return true;
} else {
alert("password not same");
return false;
}
}
and html:
<form onsubmit="return validate();" action="submit_path" >
<input type= "password" id="password" name="password">
<input type= "password" id="retype_password" name="retype_password">
<input type="submit" name="submit" value="Submit" >
</form>
Here is an easier way by using class:
password : <input type= "password" class="passwords" name="password"> <br><br>
retype password : <input type="password" class="passwords" name="retype_password" > <br><br>
In your javascript:
var passwords = document.getElementsByClassName("passwords");
function validate(){
var first = passwords[0].value;
var second = passwords[1].value;
if(first != second){
//Invalid
} else{
//Valid
}
}
Related
I am trying to make a javascript function that will not submit to the next form unless the information is input correctly i.e only numbers. Is there a way to make the HTML unclickable while the information is incorrect?
function checkInput() {
var error = false;
var phonenumber = /^\d{10}$/;
if (!document.getElementById('username').value.match(phonenumberExpression)) {
alert("Phonenumber is invalid");
error = true;
}
if (error == true) {
error = false;
}
}
<p>Phone Number:</p>
<input class='in-sel-style' id='username' type='text' class="form-control input-md" name='username' required=""><br>
<input class='in-sel-style' id="submit" type='submit' name='submit' onclick='return checkInput()'>
You can add event variable into onclick like this :
<input class='in-sel-style' id="submit" type='submit' name = 'submit' onclick = 'checkInput(event)'>
Then in your javascript function try this :
<script>
function checkInput(event){
var error = false;
var phonenumber = /^\d{10}$/;
if (!document.getElementById('username').value.match(phonenumberExpression)){
alert("Phonenumber is invalid");
error =true;
}
if(error==true){
event.preventDefault();
error=false;
}
</script>
Actually you can use HTML5 Form Validation. So just do this:
<input class='in-sel-style' id='username' type='text' class="form-control input-md" name = 'username' required="" pattern="^\d{10}$">
This will work the same way required does.
If you need a more complex thing that you can do with a regular expression you can do something like this:
document.getElementById('username').addEventListener("input", function (event) {
const value = event.target.value;
const phonenumber = /^\d{10}$/;
if (!value.match(phonenumberExpression)) {
email.setCustomValidity("Phonenumber is invalid");
} else {
email.setCustomValidity("");
}
});
a short notice, I would recommend to always use <button type="submit"> instead of <input type="submit">.
When I invoke the function it is getting invoked but it flashes the result. Could please tell me what is the mistake I did?
Below is the HTML Code I used:
I have replaced the input type as a button but still, error not fixed.
function reg() {
//Name Field
var f = document.forms["registration"]["fullname"].value;
if (f == "") {
alert("Enter the name");
return false;
} else if (!f.match(/^.[a-zA-Z]+$/))
{
alert("Enter only alphabets");
return false;
}
document.getElementById('details').innerHTML = "Hi" + registration.fullname.value;
}
<form name="registration" onsubmit="return reg()">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
Here is what I believe you want to do.
Note it is better to add an event handler in the script rather than having an inline handler, but for now I pass the form itself in the function
function reg(form) {
//Name Field
var f = form.fullname.value;
if (f == "") {
alert("Enter the name");
return false;
}
// no need for else when you return
if (!f.match(/^[\. a-zA-Z]+$/)) { // I personally have a space in my full name
alert("Enter only alphabets and space");
return false;
}
document.getElementById('details').innerHTML = "Hi " + f;
// change to true if you want to submit the form but you will then not be able to see the HI
return false;
}
<form name="registration" onsubmit="return reg(this)">
<input type="text" name="fullname" placeholder="Enter Your Full Name"><br><br>
<input type="submit" value="submit">
</form>
<span id="details"></span>
I made this code which submits a form with a name and age field with a submit button. My code looks like this:
function checkForm() {
var name = document.forms["form"]["name"].value;
var age = document.forms["form"]["age"].value;
var regName = /^[A-Z]*[a-z]{3,} $/;
var regAge = /^[\d.*]{1,} $/;
if (name == regName && age == regAge) {
return true;
} else {
return false;
}
}
<form name="form" action="register.php" method="POST" onsubmit="return checkForm()">
<p>Name:</p>
<input type="text" name="name" id="name">
<br>
<p>Age:</p>
<input type="text" name="age" id="age">
<br>
<br>
<button type="submit" name="submit">Submit</button>
</form>
The name should be using only upper case and lower case letters and the age must be numerical and a positive integer.
Supposedly, when I entered the wrong data, the form should not return false but its returning true and sending me through to register.php. Is there something wrong with my code?
Try evaluating regex With pattern.test('stringMethod')
function checkForm(event){
var name = document.forms["form"]["name"].value;
var age = document.forms["form"]["age"].value;
var regName = /^[A-Z]*[a-z]{3,} $/;
var regAge = /^[\d.*]{1,} $/;
if (regName.test(name) && regAge.test(age)){
return true;
} else{
event.preventDefault();
return false;
}
}
Try to add event.preventDefault(); when the data is invalid.
function checkForm(event){
var name = document.forms["form"]["name"].value;
var age = document.forms["form"]["age"].value;
var regName = /^[A-Z]*[a-z]{3,} $/;
var regAge = /^[\d.*]{1,} $/;
if (name == regName && age == regAge){
return true;
} else{
event.preventDefault();
return false;
}
}
Form default behaviour is like that if you are calling a function on submit it will get submit. So you can call the function on button submit.
<button type="submit" name="submit" onsubmit="return checkForm()">Submit</button>
should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp
I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>