Different errors for a single input in Foundation Abide / AngularJS

余生颓废 提交于 2019-12-24 14:23:10

问题


I'm trying to setup a form with Foundation and I'm finding it difficult to do more than basic error checking. Lets say I have the following input field:

<input pattern="username" required type="text" placeholder="username" />

Assuming the username regex is a custom pattern something along the lines of this:

^[A-Za-z]{3,6}$

What I need to be able to do is show different errors depending on whether the string in the input field is above or below that character limit. As far as I can tell Foundation Abide has issues with this. I can't find any documentation that even suggests this is possible.

On the other hand, I have AngularJS available within the same application, and could theoretically use the ng-min / ng-max directives, and switch error cases based off that. My understanding however is that Foundation and Angular don't exactly play nice with each other, and this may introduce some issues communicating between frameworks. Business requirements state I need to try and do as much of this in Foundation as possible, but if I can provide a good case as to why Foundation is not suitable then there would be leeway.

Is there a way to do what I need purely in Foundation? Is mixing the Angular and Foundation validations something that is easily done, or am I going to run into issues with Angular's $digest cycles?


回答1:


You should be able to do this by using Foundation. Abide allows you to create your own custom validation function when foundation is initialized. In that validator you can use DOM manipulation to adjust the inner text of your error message. Your initialization will look something like this:

$(document).foundation({
     abide: {
        validators: {
            myCustomValidator: function (el, required, parent) {
                if (el.value.length <= 3) {
                    document.getElementById('nameError').innerText = "Name must have more than 3 characters";
                    return false;
                } else if (el.value.length >= 9) {
                    document.getElementById('nameError').innerText = "Name must have less than 9 characters";
                    return false;
                } //other rules can go here
                return true;
            }
        }
    }
});

and you can then use this validator in your label like this:

 <form data-abide>
    <div class="name-field">
        <label>
            Email <small>required</small>
            <input type="text" data-abide-validator="myCustomValidator">
        </label>
        <small id="nameError" class="error">An email address is required.</small>
    </div>
    <button type="submit">Submit</button>
 </form>


来源:https://stackoverflow.com/questions/24129659/different-errors-for-a-single-input-in-foundation-abide-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!