I have a basic form which contains a text field like this:
But I want to control if exist any predefined word like "Mickey", If it does not exist, I want to block submitting, like validations in registration forms. This predefined word can be anywhere in textfield like "MickeyMouse" or "MouseMickey" or "MyMickeymouse".
You could use HTML5 form validation. Simply make the field required and give it a pattern. No JS required (although you might choose a polyfill for old browsers).
Try and submit this form without matching the pattern:
<form>
<input name="myInput"
required="required"
placeholder="Must contain Mickey"
pattern=".*Mickey.*"
title="It must contain Mickey somewhere."
/>
<input type="submit" />
</form>
Also: Untested example with basic JS fallback
HTML
<input type="submit" id="button" class="button" onclick="return submitcheck();" />
Script
function submitcheck() {
if(document.getElementById("textField").value.indexOf("Mickey") > -1) {
return true;
} else {
return false;
}
}
If n is not -1 then Mickey was in the string.
Assuming you have a 'text field' DOM element somewhere:
if($(<textfield>).val().indexOf($(<inputID>).val()) > -1){
//things to be done if 'Mickey' present
}
You can do this validation on click of the submit button.
Related
I have a form that I am trying to validate using HTML 5 (and jQuery).
The form has initial values that are loaded in from a database. The users can edit the data and then submit the form. I have an input box with maxlength set to 6 but sometimes the value pulled from the DB has more than 6 characters in it. If the user doesn't do anything and just clicks submit then I want an HTML 5 validation warning. But the form just submits without a warning
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
I have tried adding a pattern {0,6} but this doesn't make any difference.
I don't want the form to remove characters automatically, the user must do this.
I tried using jQuery validate, but I don't think I am doing it correctly:
$(window).on("load", function() {
const $reading01 = document.querySelector('#reading01');
$reading01.validate();
}
If you normalise the <button> (ie. give it type="button" rather than type="submit") you can take advantage of the HTML5 Constraint API for Form Validation.
The HTML5 Constraint API enables you to define your own validation constraints.
Once the form validates, you can use submit() to submit the form.
Working Example:
const checkValuesForm = document.getElementById('checkValues');
checkValuesFormSubmitButton = checkValuesForm.querySelector('[data-type="submit"]');
const checkValues = (formSubmitted = false) => {
const reading01 = document.getElementById('reading01');
if (reading01.value.length > 6) {
reading01.setCustomValidity('This number cannot be more than 6 digits long');
reading01.reportValidity();
}
else {
reading01.setCustomValidity('');
if (formSubmitted === true) {
checkValuesForm.submit();
}
}
}
checkValuesFormSubmitButton.addEventListener('click', () => checkValues(true), false);
reading01.addEventListener('keyup', checkValues, false);
window.addEventListener('load', checkValues, false);
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" />
<button class="btn btn-primary" type="button" data-type="submit">Update</button>
</form>
Further Reading
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation
https://www.sitepoint.com/using-the-html5-constraint-api-for-form-validation/
you just need to display warning or prevent going further , in that case you can do your own validation by getting id and check it is empty or not.
Like Rounin says Je sus Monica said, using setCustomValidity is the cleanest way to send a message to inform of an error on a input. Still, since you are using a submit button, you can listen to your form's submit event and validate it before send the request. Also, you can use the Document.forms read only property, which returns a collection of HTMLFormElement. I like how it looks codewise, because it is very easy to understand that you are working with a form.
const form = document.forms['checkValues'];
form.addEventListener('submit', (e) => {
e.preventDefault();
const validatedInput = form.elements['reading01'];
if (validatedInput.value.length > 6) {
validatedInput.setCustomValidity("The input value cannot be longer than 6.");
return;
}
form.submit();
});
<form id="checkValues" method="post">
<input id="reading01" name="reading01" type="text" required class="form-control" maxlength="6" value="12345678" pattern="{0,6}">
<button class="btn btn-primary" type="submit">Update</button>
</form>
One more thing, and this is just a personal taste, when naming variables, I normally add the $ symbol for jQuery elements. So if by chance I am using a jQuery library, I can identify which variable holds a plain javascript element and which a jQuery element.
I'm trying to stay away from JQuery for this one (nothing against JQuery, I just don't want to load a huge library into this project for something small like this).
I'm curious how I might tell HTML5 to recheck all the required input fields in a given form. For example, I have this form (albeit slightly more complicated but you get the point):
<form action="here" onsubmit="check()">
<input required name="something">
<input type="submit">
</form>
If I don't have anything in that required field, HTML5 shows a popup error, something to the effect of "Please fill in this required field". What is stopping the user from putting in a single space, or some nonsense character like % or >? I'd like to partially validate this client-side (in addition to server side) so it isn't particularly inconvenient when the page redirects to the form submission page and then shows the error, and then goes back to the form, prompting the user to enter everything over again.
Assuming in my onsubmit function check I've removed all whitespace and/or nonsense characters from the ends of the string, how can that function then tell HTML5 to recheck the form to see if the required fields are still not empty?
Instead of onsubmit="check()" use addEventListener.
Now you can do everything with input data.
document.getElementById("submit").addEventListener("click", function(event){
var something = document.getElementById("something").value;
document.getElementById("something").value = something.replace(/[^A-Z0-9]/ig, "");
});
<form action="here">
<input required name="something" id="something">
<input type="submit" id="submit">
</form>
try to use regexp pattern (e.g. exclude white chars: [^\s]*, allow only letters [A-Za-z]*, ...)
<form action="here" onsubmit="check()">
<input required pattern="[^\s]*" name="something" >
<input type="submit">
</form>
I am trying to reuse HTML5 validation required in simple serach form (so one input). It's exactly what I need (validation message in browser's language, styling, not allowing to progress, etc.). What I missing is trimming input string so not allowing user to submit just whitespaces.
I made research already and onsubmit event seems to be too late triggered to modify anything. I can't also make any change of actual inputs, so those has to remain intact during whole process (like with classic validation).
Is there any way to solve it with vanilla HTML5 without using libs like jQuery?
Edit: Using pattern attribute is not a solution here because it has different error message than this field cannot be empty.
You could try something along the lines of
<form method = "post">
<input type = "text" required pattern=".*[^ ].*" oninvalid="setCustomValidity('Please fill out this field')"
onchange="try{setCustomValidity('')}catch(e){}"/>
<input type = "submit" />
</form>
Otherwise if you really, really need to use only the required attribute you something like this would work for you
<form method = "post">
<input type = "text" required oninput = "if(this.value.trim() == '') { this.value = '' }"/>
<input type = "submit" />
</form>
You can use onsubmit, You just need to return false if it doesn't validate
<form onsubmit="return check()">
Enter name: <input type="text" id="myinput">
<input type="submit">
</form>
<script>
function check(){
if(document.getElementById("myinput").value.trim().length ==0){
return false;
}
return true;
}
</script>
I have a HTML page containing a form. I want to make some fields "required". The problem is that I'm not using a <input type="submit"> in my form, instead, I use a Javascript function to submit the form because I need to send a Javascript variable to my server. Here is my code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="button" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
So, Even is I have the required attribute in my input but the form is still being submitted even if I don't enter anything in the input.
Here is a JSFiddle of how I want my form to behave when clicking on the button without entering anything.
Anyone knows how form.submit() is different from having an <input> of type="submit" ?
EDIT: After following user2696779's answer and doing a little modification, here's the final working code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="submit" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
if (frm.checkValidity()) {
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
}
Your current HTML input button isn't a submit type, it's a button type. The requred attribute on your input element is therefore ignored. To change this, change your button's type to submit:
<input type="submit" value="Submit">
Browsers which support the required attribute will now display a warning when the button is clicked:
JSFiddle demo.
Submitting using javascript will not trigger any validation. If you want to submit using a regular button + javascript and still have validation, you may use HTML5's checkValidity function to verify form fields, or the entire form.
For example, using JQuery:
if(!$('form')[0].checkValidity()) {
alert('not valid');
}
else {
$('form').submit();
}
See fiddle for working example: http://jsfiddle.net/8Kmck/2/
I have a simple javascript that I can't seem to get to work.
So what I'm trying to accomplish is a text field on my homepage that the user can type in(just 1 field). Submit it and it'll take them to another page with a text field that is pre filled with what they already typed in the first field.
<script type="text/javascript">
function go_page(page)
{
document.location.href = '/?page_id=11' + '#addressInput=' + addressInput;
}
</script>
When i fill in the 'addressInput' (for this example, lets say '90501')..
Currently, the url comes up as www.mywebsite.com/?addressInput=90501
Goal, i want it to be.. www.mywebsite.com/?page_id=11#addressInput=90501
This 'goal url' works when i type it in the address bar. I just need to figure out how to do that function automatically for the user..based on what they input in the first text field.
...any ideas?
EDIT 1
Here is the form code..
<form method="get" onsubmit=" go_page(this.page.value); return false">
<input type="text" name="addressInput" id="addressInput" size="30" />
<input type="submit" value="" class="submitButton" />
</form>
EDIT 2
just more info..
The user will be on the homepage and type in an 'address/zip code' in the text field and click submit.
Which will then take them to the locations page(page_id=11) that has a text field that's pre-populated with the 'address/zip' the user typed in on the homepage.
You could try grabbing the element in the form like this
<form method="get" onsubmit="go_page(this.addressInput); return false">
<input type="text" name="addressInput" id="addressInput" size="30" />
<input type="submit" value="" class="submitButton" />
</form>
And extracting the value of addressInput inside your function like this
function go_page(elem) {
var addressInput = elem.value;
window.location.href = "/?page_id=11#addressInput"+addressInput;
}
In Wordpress that should navigate you to the page id and add the hash to the end
Its not clear from the limited information provided, but have you stopped the default form submission behavior? Maybe the form if being submitted before your javascript is called. Capture the form submission and return:false or event.preventDefault() to stop it continuing with the submission.
If you want to have # in the URL, you have to encode it so instead of using # use %23. And do not forget that for separating values in URL you have to use &.
document.location.href = '/?page_id=11' + '%23addressInput=' + addressInput;
Update
Instead of document.location.href use window.location