On a form submit trying to run a function in a controller that checks for matching passwords and if email field contains a class.
Scenerios:
If the passwords don't match it fails
If email contains ng-invalid it fails
Passwords validate just fine, the issue is trying to see if the Email field contains a class after form submit.
In jQuery would write:
if($(#email).hasClass('ng-invalid'){//email is invalid man return false;}
But in Angular not using jQuery. Tried several ways in vanilla JS to see if #email has class 'ng-invalid' but it's not working. JavaScript Check If Element Has Class
The end result is using the function "formValidate()" in Jasmine unit test to verify if formValidate() is true or false.
Basic Implementation:
PLUNKER
Jasmine (This should fail):
it('Join Now button should be enabled when form fields are valid.',
function(){
var ctrl = createController();
$httpBackend.flush();
var joinNowBtn = registrationEl.find('.join-now-btn');
$rootScope.user = {
'email': 'hola#friend.c',
'password': 'abc',
'passwordConfirm': 'abc'
};
expect($rootScope.formValidate()).toBeTruthy(); //THIS TEST SHOULD FAIL
//expect submit button to not have a disabled attribute
});
You don't need to check for ng-invalid class. Just check if $scope.registration_form.email.$invalid is true or false.
$scope.user.email.$invalid didn't work because $scope.user.email is just a string.
Form validation information is put into $scope.formName. You can use the following:
$scope.formName.$invalid === true
$scope.formName.fieldName.$invalid === true
Check NgModelController docs.
You can use hasClass()
Angular natively has access to jqLite's hasClass().
http://docs.angularjs.org/api/angular.element
You shouldn't need to be checking classes a la jQuery. You can check the validity of the form input by passing the form into your submit function and checking to see if email.$invalid is true or false. So something like this:
html
ng-submit="submitForm(this.registration_form)"
js function
$scope.formValidate = function(form){
if(form.email.$invalid){
alert('email is invaid')
return;
}
// etc.
}
Related
Basically I'm using this tutorial: HTML FORM
Everything is working as it should but one flow I've found is that everyone can see the URL for your .php which in this case is "url: "contact_mail.php""
Is there a way to protect my form from blank submission when someone type the url and just press enter.
Example: www.mywebsite.com/contact_mail.php
Thank you!
First you can use the required attribute on mandatory fields for client-side:
<input type="text" name="mandatory_field" required>
But you will need to verify server-side in case the user modified the form. You can use empty() on any variable ($_POST or $_GET):
if (empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
You can use isset() to verify if a field is submitted. Your validation could be:
if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
Other cases:
If all fields are mandatory you could check with in_array():
if (in_array(false, $_POST)) {
// print error message or redirect to form page
}
If doing various data validation here is what I use to do with forms:
$errors = [
'empty field' => empty($_POST['field']),
'another error message' => $another_condition
];
if (in_array(true, $errors)) {
$error_message = array_search(true, $errors);
// print or redirect, and you can tell the user what is wrong
}
Say you have the following form;
<form action="savething.php" method="GET" name="mythingform">
<input name="thing1" type="text" />
<input name="thing2" type="text" />
<input type="button" value="Submit" onclick="validateAndSubmit()" />
</form>
In this, instead of a submit type input, I have used a button. This means, something needs to happen before the page will submit, so, for example;
<script>
function validateAndSubmit()
{
var thing1 = document.getElementsByName("thing1")[0];
var thing2 = document.getElementsByName("thing2")[0];
if (thing1.value.length > 0 && thing2.value.length > 0)
{
document.forms["mythingform"].submit();
}
}
</script>
The JavaScript function here will only call the submit on the form when the inputs are not empty
In terms of stopping someone from accessing this without permission;
<?php
if (!isset($_REQUEST['myvariable'] || empty($_REQUEST['myvariable']))
die("Please make sure the form has been submitted properly with all required information");
Using die in this, will terminate execution of the script any further, you can also use exit and both allow you have have a "termination message" attached to them as part of the stoppage process
$_REQUEST isn't the safest of options, but it permits you to use GET or POST methods from forms to be able to retrieve and use data
Form blank submission you can use java-script validation or jquery validation validation or you can also use php validation to avoid blank form submission.
core js validation
simple example:
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
jquery validation
validation library
https://jqueryvalidation.org/documentation/
example:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
I hope it helps.
(1) there should be no danger from someone 'just entering' the URL in their browser - the back-end code is supposed to respond only to POST, not to GET (entering a URL in a browser makes it issue a GET request for the given URL).
(2) the quoted example code already includes client-side validation (including checks for empty fields), so if someone legitimately uses your entry form, they will not be able to send a blank form.
(3) all that remains is to protect the back-end code from accidental or malicious posting of empty forms (and any other use that is undesirable). The example PHP code doesn't have any checks, you should add some - like the isset(...) or empty() checks suggested in another answer here).
Use if (empty($_POST['your_field']))
So if a post or get query reaches your php script, empty will check if the field is empty or not.
So something like this:
if (empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Although isset would be better, since if they just go to the link, your POST and GET variables are empty.
So something like this is kinda foolproof:
if (!isset($_POST['your_field']) || empty($_POST['your_field'])) {
echo 'Field xxx should not be empty';
}
Didn't think i'd need a separate piece of code for GET, but ok.
if (!isset($_GET['your_field']) || empty($_GET['your_field'])) {
echo 'Field xxx should not be empty';
}
This is more of a broad question, but I'm working on some form validation functions in Javascript. Instead of using alerts I have been told to use the error fields in the JSP, but where ever I look for information on form validation it simply shows an alert being thrown.
So if I have something like this to check for only letters in a name field
function allLetter(inputtxt)
{
var letters = /^[A-Za-z]+$/;
if(inputtxt.value.match(letters))
{
alert('Your name have accepted : you can try another');
return true;
}
else
{
alert('Please input alphabet characters only');
return false;
}
Then I want to use the
<form:errors path= "firstName"/>
to throw the error that the function is getting whether that means the field is blank or a number has been entered, but how do I go about that?
To use form:errors tag in JSP, you should do server side validation.
I think in your question you refferred to using client side javascript validation right?
Here is a similar example showing server side validation and form:errors within JSP:
Spring Validator - show errors using <form:errors
Dudes! I've a POST form one field of this is:
<input type="text" name="username" />
In jQuery I placed var called var username = <---code here--->;
The question is how to interactively pass the INPUT field value to this var before user hit the Submit button?
Try:
$("input[name='username']").blur(function() {
var username = $(this).val();
});
Do you mean something like this
The jQuery selector that will find that field is:
var username = $('input[name="username"]').val();
To assign the variable before the form is submitted, you could follow Sudhir's answer, or capture it when the form is submitted:
$(function() {
$('#yourFormid').submit(function() {
var username = $('input[name="username"]', this).val();
// do work
return true; // true to submit the form, false to cancel submission
});
});
Here's another approach that updates the variable as the user types.
A live demo can be found here: http://jsfiddle.net/EnS8T/11/
var username = "";
$(document).ready(function()
{
$("[name='username']").keyup(function()
{
username = $(this).val();
});
});
Other functions, besides keyup(), that can be used include keydown() and keypress(). The behavior of these three functions can be observed in the jsFiddle above.
By interactively, do you mean as typed? Then use onKeyPress event on your textbox. You might have to do something strange, like create a setTimeout, if you don't want to write a lot of code to monitor cursor position.
I'm trying to write a custom validation that gives an error if html exists in the textarea when they submit a form.
I have the following -
its not working and I'm not sure why.
also I don't understand the unobtrusive part
can someone show me how to do that as I am seeing other examples on SO that have it.
text area has a class"note"
the form is called "noteform"
<script type="text/javascript" >
$(document).ready(function () {
$.validator.addMethod('nohtml', function (value, element) {
var text = $(".note").text();
if ($(text).length > 0) {
return false;
}
else {
return true;
}
}, 'Html not allowed');
// // **not sure what to do here**
// $.validator.unobtrusive.adapters.add('containsnohtml', {}, function (options) {
// options.rules['nohtml'] = false;
// options.messages['nohtml'] = options.message;
// });
$('#noteform').validate({
rules: { nohtml: "required nohtml" }
});
});
</script>
There's a couple issues here. One is you're trying to mix unobtrusive and regular jquery validation. If you want to use validate like this then you need to make sure jquery.validate.unobtrusive.js is NOT included. This is because jquery.validate.unobtrusive.js automatically parses and produces a validator for the document and the very first thing that validate does is check if there's an existing validator and exits if there is.
If you do decide to go the non-unobtrusive route, be sure not to use the $.validator.unobtrusive.adapters.add since it will cause an error without jquery.validate.unobtrusive.js.
I would recommend going with unobtrusive validation though since I think you're using MVC3.
If you're going to go with unobtrusive validation you have two choices, set the data-* attributes yourself by adding data-val="true" data-val-nohtml="Html not allowed" to your textarea as suggested by JohnnyO and including a span with data-valmsg-for="note" data-valmsg-replace="true" to show the error message. Or you can make your own DataAnnotation attribute.
Here's the code for the addMethod (needed for both kinds of validation)
<script type="text/javascript">
(function ($) {
$.validator.addMethod('nohtml', function (value, element) {
// Test 'value' for html here. 'value' is the value of the control being validated.
return true; // Return true or false depending on if it passes or fails validation, respectively.
}, 'Html not allowed');
} (jQuery));
</script>
and the javascript needed for the unobtrusive is as follows
$.validator.unobtrusive.adapters.addBool('nohtml');
Regarding how to make a custom validation attribute, since I'm not sure what language you're using, assuming you're using MVC3, or if you even need this info anymore 4 months after you asked, I'm going to simply leave these links for reference.
A brief comparision of Traditional vs Unobtrusive JavaScript Validation in MVC 3 - Mitchell Trent's Blog
ASP.NET MVC 3 Custom Validation - Microsoft Developer Network
Although I haven't tested this, I think all you're missing is to wire up the element that you want to validate with the nohtml rule. Something like this:
$('textarea.note').rules('add', {
nothml: true
});
Based on some of your description, I assume you're using ASP.NET MVC3. In that case, you would only need to use the unobtrusive adapter if you're generating the validation attributes server side on your html element (e.g. <textarea data-val="true" data-val-nohtml="Html not allowed"></textarea>). In such a case, you'll need the unobtrusive adapter to wire up the element to use your nohtml rule.
I've got a form that can optionally be pre-populated via facebook connect. Once a user connects, their name and email are automatically filled in. The problem is that this doesn't trigger the remote validation to check if the email already exists.
Is there a way I could call the validation on that field alone? Something like:
$('#email-field-only').validate()
would be idea. Searched through the docs with no luck.
This method seems to do what you want:
$('#email-field-only').valid();
Edit
API has changed, see Paul's answer.
Use Validator.element():
Validates a single element, returns true if it is valid, false
otherwise.
Here is the example shown in the API:
var validator = $( "#myform" ).validate();
validator.element( "#myselect" );
.valid() validates the entire form, as others have pointed out. The API says:
Checks whether the selected form is valid or whether all selected
elements are valid.
$("#FormId").validate().element('#FieldId');
For some reason, some of the other methods don't work until the field has been focused/blured/changed, or a submit has been attempted... this works for me.
$("#formid").data('validator').element('#element').valid();
Had to dig through the jquery.validate script to find it...
If you want to validate individual form field, but don't want for UI to be triggered and display any validation errors, you may consider to use Validator.check() method which returns if given field passes validation or not.
Here is example
var validator = $("#form").data('validator');
if(validator.check('#element')){
/*field is valid*/
}else{
/*field is not valid (but no errors will be displayed)*/
}
When you set up your validation, you should be saving the validator object. you can use this to validate individual fields.
<script type="text/javascript">
var _validator;
$(function () {
_validator = $("#form").validate();
});
function doSomething() {
_validator.element($('#someElement'));
}
</script>
-- cross posted with this similar question
in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:
$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();
Hope it help everybody :)
EDITED
$("#element").validate().valid()