Add validation only for capital letter and numbers - javascript

If user have used small letter in the field then validation is working like
aBCD1234
Not working means form will not submit
ABCD1234
Now user will submit the form.

No need to use JavaScript (and especially not jQuery):
<input type="text" pattern="[A-Z0-9]{8}" />
Adjust the pattern as needed, but this will stop form submission of invalid input, even when JavaScript is disabled. It's also simpler to program.
MDN Doc on HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

How about:
<input type="text" onkeyup="this.value = this.value.toUpperCase();" />

Add return isValid(); in the onclick event of the submit button:
<input type="button" onclick="return isValid();" />
The isValid function is described well in #janaspage's answer

Related

Prevent double submission AND allow "required" fields

Starting off with a simple form that requires an email address:
<form action="NextPage.php" method="post">
<input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email">
<button type="submit">Submit</button>
</form>
(Non-essential features like labels and other fields have been removed for troubleshooting purposes.)
Some time ago, I was having trouble with double submission. I remember trying many different solutions, but the only one to work I found here.
So, I implemented that solution:
<form action="NextPage.php" method="post">
<input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email">
<button type="submit" onclick="this.form.submit(); this.disabled = true;">Submit</button>
</form>
This was over a month ago, and I forgot all about it until just now. The "required" attribute now doesn't do anything as this.form.submit(); seems to override required.
A lot of the solutions to this problem require a lot of plugins or extra features, but is there an elegant solution?
The most elegant solution possible would be pure html, but I expect I'll need javascript also. I'd like to avoid downloading libraries or installing plugins if at all possible.
Examples:
Solution using angularJS
Solution using jQuery
All I want is a form that doesn't submit twice on double clicking, and honours the required attribute. Ideally without having to learn a new library or markup language. I wouldn't mind writing a couple of lengthy javascript functions if I needed to. Even a page that redirects to the next page wouldn't be too inelegant.
(I also know PHP and SQL, but I don't think either of them would help here.)
Is this even possible?
Instead of disabling the button in the onclick attribute of the button, disable it in the onsubmit attribute of the form.
You need to give the submit button a name, and then you can refer to it as this.<name> in the onsubmit attribute. Or you could give it an ID, then you could use document.getElementById("<id>") to refer to it.
<form action="NextPage.php" method="post" onsubmit="this.submitButton.disabled = true;">
<input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email">
<button type="submit" name="submitButton">Submit</button>
</form>
The reason your code needed to call this.form.submit() is because clicking on a disabled button doesn't trigger the default form submission. But if you put the disabling code in the onsubmit attribute, it only runs once the form submission process has started.
For jQuery fans:
$('form').submit(function(){
$(':submit').attr('disabled','disabled');
});

HTML5 Required input, removing and adding on the fly not working

I am trying to remove a required attribute from an input on the fly. The general idea is I have a field that is set to required, this field has custom validation with the pattern attribute. When the user clicks a button I am attempting to remove the required field.
I have put together a fiddle here:
https://jsfiddle.net/paulmatos/t1p1wub3/
HTML:
<form>
<input type="text" oninvalid='this.setCustomValidity("Enter a number in the Specified Range");' oninput="try{setCustomValidity('')}catch(e){}" pattern="[0-9]" required="required" name="password" id="password" />
<input type="text" required="required" name="temp" />
<input type="submit" class="btn btn-primary form-control" value="Submit" />
<div class="btn btn-default removeReq">Remove Required</div>
</form>
Jquery:
$('.removeReq').click(function() {
$('#password').removeAttr('required');
});
The issue I am experiencing has to do with the order of submission.
If you click remove required, and then submit the form you will see that it works as intended.
However, if you do those steps in reverse order, click submit first, then remove and try and submit again, you will notice I am still getting the validation error on the first input.
Is there anyway to get around this with this intended functionality, I am trying to get this to work just with the html5 validation.
I did have a look at the fiddle and the only way I could get the behaviour you wanted was by literally detaching, cloning and reinserting the field. Works tho.
$('.removeReq').click(function() {
var password = $('#password').removeAttr('required oninvalid oninput pattern').detach().clone();
$('form').prepend(password);
});
https://jsfiddle.net/t1p1wub3/2/
Think you are getting this due to the code in the oninvalid handler. Try this.
$('.removeReq').click(function() {
$('#password').removeAttr('required oninvalid');
});
You can try this instead of removeAtt():
$('.removeReq').click(function() {
$('#password').prop('required', false);
});

How to use Pattern Attribute on Textbox

I am trying to use Pattern attribute to do validation on text box.
When ever user entered any of these .....i want to show some validation message.
So i created that element as follows:
<input type="text" pattern="/(<!|&#|<\?|<|>)/" title="Required" required />
When ever i entered any text it is showing the alert...
How to get rid of this?
You were using the wrong pattern. In HTML patterns, you don't need an opening and closing delimiter. Also, the browser checks, if the entered text MATCHES the pattern, but you would need the exact opposite (if I understood it correctly). Try something like this:
<form>
<input type="text" pattern="^((?!(<)|(<!)|(<\?)|(&#)|(>)).)*$" title="Required" required />
<input type="submit" />
</form>

Check if checkbox is checked then send

I have this markup:
<form action="http://acumbamail.com/signup/13565/" method="POST">
<input type="checkbox" id="privacidad-btn" > Acepto polĂ­tica de privacidad<br>
<input type="button" value="Enviar" id="submit_acumba">
</form>
I want that if the user clicks on the button without checkbox checked there is an alert that he must agree to the terms (check the checkbox). Any ideas on the best approach to this?
I'm starting doing this way but don't know how which way to go:
if (jQuery("#privacidad-btn").is(":checked")) {
}
One approach that i like with html5 is the form validation
just put required on the checkbox and when the try to submit it they will be alerted with a popover dialog in there own language (its a good highlighter in the form of what is wrong with it)
<input required type="checkbox" id="privacidad-btn">
You could do it the way tymeJV suggest with button clicked event $("#submit_acumba").click(...)
That way you would support more browsers. but: It would just only validate on a click of a button
But there is the form submit event as well.
$("form").submit(function(e) {
if ( ! jQuery("#privacidad-btn").is(":checked")) {
// Not checked abort the default submit
e.preventDefault();
}
});
The difference is that it has to do all the native form validation before -> if it is invalid it won't trigger a submit or call the function
with button.onclick it would avoid the native validation since it would run before the submit event
You need a handler for the button as well:
$("#submit_acumba").click(function(e) {
e.preventDefault();
if (jQuery("#privacidad-btn").is(":checked")) {
//submit!
}
})
Using this straight and simple HTML implementation, you can do this without any special scripting (JavaScript/jQuery):
<form>
<p><input type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
Here's a JSFiddle link where you can play with this implementation: http://jsfiddle.net/zs9b167b/

Javascript login form doesn't submit when user hits Enter

I'm working on a simple javascript login for a site, and have come up with this:
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify.
1. Your Immediate Concern:
(Why won't the input button work when ENTER is pressed?)
Use the submit button type.
<input type="submit".../>
..instead of
<input type="button".../>
Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
2. Security concerns:
#Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.
Is there some way I can do a user validation client-side?
Encrypting Ajax calls for authentication in jQuery
3. Other Issues:
Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).
The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
Instead of <input type="button">, use <input type="submit">. You can put your validation code in your form onsubmit handler:
<form id="loginwindow" onsubmit="validate(...)">
it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.
<input type="password" name="text1" onkeypress="detectKey(event)">
Maybe you can try this:
<form id="loginwindow" onsubmit='validate(text2.value,"username",text1.value,"password")'>
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="submit" value="Check In"/>
</p>
</form>
As others have pointed out, there are other problems with your solution. But this should answer your question.
Surely this is too unsecure as everyone can crack it in a second ...
-- only pseudo-secure way to do js-logins are the like:
<form action="http://www.mySite.com/" method="post" onsubmit="this.action+=this.theName.value+this.thePassword.value;">
Name: <input type="text" name="theName"><br>
Password: <input type="password" name="thePassword"><br>
<input type="submit" value="Login now">
</form>
My Thought = Massive security hole. Anyone can view the username and password.
More relevant to your question: - You have two events happening.
User clicks button.
User presses enter.
The enter key submits the form, but does not click the button.
By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.
Your code will then run for both events.

Categories

Resources