validate input with js - javascript

this is my register.php code
<form id="register_form" onsubmit="return false" autocomplete="off" >
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" placeholder="enter username">
<small id="u_error" class="form-text text-muted"></small>
</div>
<button type="submit" name="user_register" class="btn btn-primary"><span class="fas fa-user"></span> Register</button>
this is my js
$(document).ready(function(){
// alert("hello friends");
$("register_form").on("submit",function() {
var status = false ;
var name = $("#username");
if (name.val() == "" || name.length < 6 ) {
name.addClass("border-danger");
$("#u_error").html("<span class='text danger'> name more that 6 char</span>");
status = false;
}else {
name.addClass("border-danger");
$("#u_error").html("<span class='test danger'> please enter name</span>");
status = true;
}
})
})
here i try username field less than 6 or empty through js i validate but its not working may i know why?

There are so many changes into you code.
1.html - add submit button with </form>
2.js - your event is on '#register_form' instead of 'register_form'
3.js - To prevent on submit you have to return true or false..in you case return status; after if-else
4.js - use name.val().length instead of name.length

Nothing happens because you are submitting the form, causing a redirect to another page or to the same page in order to do things with the backend on the server.
In order to prevent the form from submitting, do the following:
$("register_form").on("submit",function(event) {
event.preventDefault();
//... rest of your code
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
Event.preventDefault()
Besides, you are now checking if the value of name is empty, or the count of elements with id username is less than 6. To check the length of the value of name, do the following:
name.val().length < 6

count length on value not on object, change name.length to name.val().length
if (name.val() == "" || name.val().length < 6 ) {
Instead I suggest change here
var name = $("#username").val();
and check like below, there is no need to check for empty, only name.length < 6 is enough
if (name.length < 6 ) {

$(document).ready(function(){
$('#frm').submit(function(){
if(!$('#name').val()){
alert('Please enter your name');
}
else if(!$('#age').val()){
alert('Please enter your age');
}
else if(!$('#mobile').val()){
alert('Please enter your mobile');
}
else if(!$('#email').val()){
alert('Please enter your email');
}
});
});
<html>
<head>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="frm">
<input type="text" name="name" id="name" placeholder="Name..."><br><br>
<input type="number" name="age" id="age" placeholder="Age..."><br><br>
<input type="number" name="mobile" id="mobile" placeholder="Mobile..."><br><br>
<input type="email" name="email" id="email" placeholder="Email..."><br><br>
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>

Related

Why does my submit button refuse to submit?

So I made a code that reads the name and password form in html. In java script I made code to ensure that the name and password fields are filled in. It also records that if the password value is less than or equal to 6 a message would display "Password must be longer than 6 characters" and if the password value is greater than or equal to 15 a message would display "Password must be shorter than 15 characters" (extra: for whatever reason when I put a 6 character password it would display that message despite the operator I included same goes for the latter).
Here's the HTML Code Followed by the javascript:
<!--Error container-->
<div id="error"></div>
<!--Form-->
<form id="form" action="/" method="GET">
<fieldset>
<!--Legend-->
<legend>Form: </legend>
<!--Name-->
<label for="name">Name:</label>
<input type="text" name="Name" id="name">
<br><br>
<!--Password-->
<label>Password: </label>
<input type="password" name="password" id="password">
<br><br>
<!--Submit and Reset Button-->
<input type="submit" Value="Submit">
<input type="reset" Value="Reset">
</fieldset>
</form>
<!--form-->
[Filler text: I thought I made the question as simplistic and easy to follow as it needs to be]
Here's the javascript portion.
The first four lines gets the id from the html code dropped from above and then the magic happens from there.
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) =>{
let messages = []
if(name.value === '' || name.value == null){
messages.push("Name is required")
}
if(password.value.length <= 6){
messages.push("Password must be longer than 6 characters")
}
if(password.value.length >= 15){
messages.push("Password must be shorter than 15 characters")
}
if(messages.length > 0){
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
e.preventDefault()
})
Please stick to Javascript and html
And thank you for using your time to read and lend a hand.
Your form won't submit because you're actively preventing it from doing so using e.preventDefault()
I would either just remove that or trigger a submit action via JavaScript if no errors occur:
if (!messages) //the variable messages is empty, so there are no errors
form.submit() //submit the form
This might also help you:
How can I submit a form using JavaScript?
Just a few minor things:
<= 6 is what's causing it to still show the error message when it's exactly 6 characters. Updating it to < 6 will only show the message when the password is less than 6 characters (as opposed to less than or equal to)
The e.preventDefault() is still being called, even outside of the error check
The messages array is never reset, so even once the user has fixed all errors, the form is still being prevented from submitting
Here's an updated version:
const name = document.getElementById('name')
const password = document.getElementById('password')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')
form.addEventListener('submit', (e) =>{
let isValid = true;
let messages = []
if(name.value === '' || name.value == null){
messages.push("Name is required");
isValid = false;
} else if(password.value.length < 6){
messages.push("Password must be longer than 6 characters");
isValid = false;
} else if (password.value.length >= 15){
messages.push("Password must be shorter than 15 characters");
isValid = false;
}
if(!isValid){
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
})
<!--Error container-->
<div id="error"></div>
<!--Form-->
<form id="form" action="/" method="GET">
<fieldset>
<!--Legend-->
<legend>Form: </legend>
<!--Name-->
<label for="name">Name:</label>
<input type="text" name="Name" id="name">
<br><br>
<!--Password-->
<label>Password: </label>
<input type="password" name="password" id="password">
<br><br>
<!--Submit and Reset Button-->
<input type="submit" Value="Submit">
<input type="reset" Value="Reset">
</fieldset>
</form>
<!--form-->
Side note: In real life, you never want to restrict the length of the users password. Let them make it as strong as they like. You're going to hash it anyway, so length and special characters won't be an issue for storage.

Validate user inputs before submit form

I have this code to validate inputs:
<script>
function validate()
{
var firstName = document.form.fullname.value;
var lastName = document.form.fullname.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword = document.form.conpassword.value;
if (firstName == null || firstName == "")
{
alert("Firstname can't be blank");
return false;
} else if (lastName == null || lastName == "")
{
alert("Lastname can't be blank");
return false;
} else if (email == null || email == "")
{
alert("Email can't be blank");
return false;
} else if (password.length < 6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
And this is my form:
<form name="form" action="<%=request.getContextPath()%>/register" method="post">
<div class="container">
<div class="left">
<div class="header">
<h2 class="animation a1">Register now</h2>
<h4 class="animation a2">Enter information in field and create account!</h4>
</div>
<div class="form">
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name...">
<input type="text" name="lastName" class="form-field animation a3" placeholder="Last name...">
<input type="email" name="email" class="form-field animation a3" placeholder="Email adress...">
<input type="password" name="password" class="form-field animation a4" placeholder="Password">
<button class="animation a6" value="Submit" type="submit">REGISTER</button>
</div>
</div>
<div class="right"></div>
</div>
</form>
How to implement that function to my form? Because now when I click submit, in my database an empty user is added. I want to add that it throws out an error in each field if it is not validly filled in
You can get the validate function to execute by adding an 'onsubmit' to your form html tag ( see here w3 Schools for executing a function on submit: onsubmit in forms)
As for the errors, when executing the code, the function cannot read a property 'value' of undefined. So what is happening is that you are telling the validate function to get parts out of the form out that it cannot find (fullname and conpassword are not defined).
Take a look at your form's name tags for fields and then reference those names in the validate function. So when declaring firstName instead of document.form.fullname.value try document.form.firstName.value referring in the form. Do this for first and last name using their names in the form, and also get rid of (or comment out) the conpassword variable.
This validation could be done without javascript function. Use the "required" tag for the inputs which are mandatory.
For example :
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name..." required>
In case of password you may use the pattern attribute.
If you need to use javascript in particular, then go for onclick in the button tag.
<button class="animation a6" onclick="validate()">REGISTER</button>
and include the form submit in the javascript function -
document.form.submit();

Why is "enter" not working for my form?

Here is the code, I can't figure out why enter/return isn't working! Is it because it's inline?
HTML
<div class="wrap"><form name="login" style="margin: 0px">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<input TYPE="text" NAME="pass" size="17" onKeyDown="e.keyCode == 13;" id="fname" class="cool"><br><input type="button" value="LOGIN" class="asbestos-flat-button" onClick="TheLogin(this.form)">
</form>
</div>
JS
<script language="JavaScript" type="text/javascript">
<!--- PASSWORD PROTECTION SCRIPT
function TheLogin() {
var password = 'password';
if (this.document.login.pass.value == password) {
top.location.href="home.html";
}
else {
location.href="index.html";
}
}
// End hiding --->
</script>
I'm learning JS so any help would be so awesome!
UPDATE
Thanks for your help. Still not working when integrated. The page doesn't load the home.html when I hit enter/return. Instead I get no refresh, and the address bar has the url http://example.com/?pass=password.
If I click the button it does load the home.html!
thanks!
Here I wrote a JSFiddle with the working example.
In the HTML code:
Remove onKeyDown="e.keyCode == 13;" from the <input> text element.
Remove onClick="TheLogin(this.form)" from the <input> button element.
Change the type of input button from 'button' to 'submit'. In this way, when you press "enter" in the input text form the form is submitted.
Intercept the "submit" event in the form, adding onSubmit="theLogin(this.form)" on <form> element.
Note: I have renamed the function name from "TheLogin" to "theLogin" because in JavaScript the functions begins with lowercase letters if they are not constructors.
The HTML code:
<div class="wrap">
<form name="login" style="margin: 0px" onSubmit="theLogin(this.form)">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<INPUT TYPE="text" NAME="pass" size="17" id="fname" class="cool">
<br>
<input type="submit" value="LOGIN" class="asbestos-flat-button">
</form>
</div>
And the JavaScript code:
theLogin = function() {
var password = 'password';
if (this.document.login.pass.value === password) {
top.location.href = "home.html";
} else {
location.href = "index.html";
}
}
You have missed the <input type="submit">, without it you can't use the Enter key to submit the form.

My javascript form validation works perfectly in Chrome but not in Firefox

The javascript:
function validateForm()
{
var x=document.forms["newsletter"]["agree"].value;
if (newsletter.agree.checked != 1)
{
alert("Checkbox must be checked");
return false;
}
var y=document.forms["newsletter"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert("Not a valid e-mail address");
return false;
}
else
{
return true;
}
}
And my HTML
<div id="signup">
<form id="newsletter" action="" method="get" onsubmit="return validateForm()">
<fieldset>
<p>Email: <input type="text" name="email" size="35"/>
Please send me the monthly newsletter
<input type="checkbox" checked="checked" name="agree" value=""/>
<br/>
<input type="submit" value="Signup"/></p>
</fieldset>
</form>
</div><!-- signup -->
When I click submit with invalid entries in Chrome, the alert messages show and the form doesn't submit. However, when I do the same in Firefox, the form submits without an alert message.
I've been working on this for 5 hours, I truly have no idea. Thanks for any help, it's greatly appreciated.
I think it might help you.
<div id="signup">
<form id="newsletter" action="" method="get" onsubmit="return validateForm()">
<fieldset>
<p>Email: <input type="text" name="email" id="email" size="35"/>
Please send me the monthly newsletter
<input type="checkbox" checked="checked" name="agree" id="agree" value=""/>
<br/>
<input type="submit" value="Signup"/></p>
</fieldset>
</form>
</div><!-- signup -->
function validateForm()
{
var agreeEl = document.getElementById("agree");
if (agreeEl.checked != 1)
{
alert("Checkbox must be checked");
return false;
}
var emailEl = document.getElementById("email");
var atpos = emailEl.value.indexOf("#");
var dotpos = emailEl.value.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= y.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
First, is there some reason you are using 'get' instead of 'post' to submit your form? Chrome complains to me when I tried to submit your form using 'get'.
I setup a simple fiddle to test your form at http://jsfiddle.net/jsWyw/. Everything works fine if I use JQuery to handle the form submit instead of your 'onSubmit'. So I looked into what was going on with onSubmit and came across this thread: http://productforums.google.com/forum/#!topic/chrome/Z3MD5Od3oQM.
Things to try:
Make sure to use post instead of get
Use 'onSubmit' instead of 'onsubmit'
Make sure your script is included using <script type="text/javascript" src="javascript.js"></script>
If that fails, I would suggest handling the submit event yourself in Javascript instead of using onSubmit which seems to be a bit flaky in Chrome.
Did you look at your error console? Your validateForm handler is assuming that window.newsletter is a form element (instead of using document.forms["newsletter"] in that first if()), which it's not in Firefox in standards mode. So that line throws, and if an onsubmit handler throws the form will just go ahead and submit. But of course the error console is reporting that the handler threw.....
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

Javascript form validation not working

I can't understand why my javascript isn't working... Do i need to declare a variable somewhere?
<script type="text/javascript">
function validation(form) {
      
if(form.first_name.value == '' ) {

alert('Please enter your first name');
 form.first_name.focus();
return false;
}
if(form.00N30000006S4uq.value == '') {

alert('Please enter the high end of your budget');
 form.company.focus();
return false;
}
return true;
}
</script>
<form action="https://www.salesforce.com/servlet/servlet.WebToLead" method="POST" onsubmit="return validation(this);">
As mentioned by #ReturnTrue, the NAME must begin with a letter. That is why your script is failing.
In your case since the field is auto-generated, if you know the flow of the elements in the form then you can reference the form elements array, like this...
form.elements[2].value
where form.elements[2] is form.00N30000006S4uq. That will do the job.
Example:
function validation(form) {
if(form.elements[0].value == '' ) {
alert('Please enter your first name');
form.first_name.focus();
return false;
}
if(form.elements[2].value == '') {
alert('Please enter the high end of your budget');
form.company.focus();
return false;
}
return true;
}
<form action="" method="POST" onSubmit="return validation(this);">
<input type="text" name="first_name" />
<input type="text" name="company" />
<input type="text" name="00N30000006S4uq" />
<input type="submit" name="submit" />
</form>
Form names need to begin with a letter. "00N30000006S4uq" fails because it begins with a number.
See: http://www.w3.org/TR/html401/types.html#type-cdata

Categories

Resources