需要只需要一组带有Parsley的字段中的一个

时间:2014-09-04 18:07:49

标签: parsley.js

我正在使用Parsley.js验证项目的表单提交。我的一个需求是让Parsley要求三个字段中至少有一个字段包含数据,如果这三个字段都没有数据,则只能通过验证。

我不确定从文档中,如何实现这一目标。我已经对表格的其余部分进行了Parsley验证。

3 个答案:

答案 0 :(得分:0)

我的建议是使用属性添加隐藏的checkbox元素:

  

数据香菜-mincheck = “1”

现在只需添加javascript代码,在表单输入有值时(相反)检查隐藏的checkbox属性。

请注意,您需要在隐藏的复选框中添加额外的属性:

  

data-parsley-error-message =“请填写至少一个输入”

答案 1 :(得分:0)

另一种方法是使用data-parsley-groupisValid({group,force})方法。

<input type="text" name="input1" data-parsley-group="group1">
<input type="text" name="input2" data-parsley-group="group2">
<input type="text" name="input3" data-parsley-group="group3">

$('#myform').parsley().on('form:validate', function (formInstance) {
    if(formInstance.isValid({group: 'group1', force: true}) || 
       formInstance.isValid({group: 'group2', force: true}) ||
       formInstance.isValid({group: 'group3', force: true})) {
       //do nothing
    }
    else {        
        $('#errorContainer').html('You must correctly fill at least one of these three groups!');
        formInstance.validationResult = false;
    }
});
  1. 您可以根据需要添加尽可能多的欧芹属性,例如data-parsley-type="email",当给定输入不为空时,将对其进行验证。

  2. 我们设置了force: true,因为它甚至在非required.fields上强制验证。

  3. 需要使用errorContainer的html呈现,因为isValid方法不会影响UI或触发事件。

答案 2 :(得分:0)

你可以使用像这样的自定义验证器

 static func inflateProfileImageFunder(view:UIView) {
    let content = ProfileImage()
    view.addSubview(content)
    content.translatesAutoresizingMaskIntoConstraints = false
    let leadingDeviceData = NSLayoutConstraint(item: content, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
    let trailingDeviceData = NSLayoutConstraint(item: content, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
    let heightDeviceData = NSLayoutConstraint(item: content, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0)
    let topDeviceData = NSLayoutConstraint(item: content, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0)
    NSLayoutConstraint.activate([leadingDeviceData, trailingDeviceData, heightDeviceData, topDeviceData])

    let isFunder = LoginVC.isFunder
        if (!isFunder){
            print("Not a Funder")
            content.buttonViews.translatesAutoresizingMaskIntoConstraints = false
            content.buttonViews.heightAnchor.constraint(equalToConstant: 0).isActive = true
            content.buttonViews.isHidden = true
        }else{
            content.label2.isHidden = true
            content.label1.isHidden = true
            content.buttonTap.isEnabled = true
            content.buttonTap.setTitle("Pledge Interest", for: UIControlState.normal)
            content.buttonTap.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: UIControlState.normal)
            content.buttonTap.addTarget(self, action: #selector(pledgeInterestView), for: UIControlEvents.touchUpInside)
    }
}

static func pledgeInterestView(){
    pledge()
}

static func pledge() {
    let content = PledgeInterest()

    content.translatesAutoresizingMaskIntoConstraints = false
    content.heightAnchor.constraint(equalToConstant: 175).isActive = true
    let attributedString = NSAttributedString(string: "I can Provide", attributes: [
        NSForegroundColorAttributeName : #colorLiteral(red: 0.1657446325, green: 0.3779471517, blue: 0.6579626203, alpha: 1)
        ])
    let alert = AlertController(title: "", message: "")
    alert.setValue(attributedString, forKey: "attributedTitle")

    let okAction = AlertAction(title: "Pledge", style: .normal, handler: nil)
    let cancelAction = AlertAction(title: "Cancel", style: .normal, handler: nil)

    alert.add(cancelAction)
    alert.add(okAction)
    alert.contentView.addSubview(content)

    content.leftAnchor.constraint(equalTo: alert.contentView.leftAnchor).isActive = true
    content.rightAnchor.constraint(equalTo: alert.contentView.rightAnchor).isActive = true
    content.centerXAnchor.constraint(equalTo: alert.contentView.centerXAnchor).isActive = true
    content.topAnchor.constraint(equalTo:alert.contentView.topAnchor).isActive = true
    content.bottomAnchor.constraint(equalTo: alert.contentView.bottomAnchor).isActive = true

    alert.view.tintColor = #colorLiteral(red: 0.1657446325, green: 0.3779471517, blue: 0.6579626203, alpha: 1)

    alert.present()

}

然后将parsley属性添加到字段组中,如下所示:

var CheckReccursion = 0;
    window.Parsley.addValidator('min3', {
        validateString: function (value, requirement, instance) {
            var notice =$('#notice').html(' ');

            var group = $(requirement);//a class

            var FieldsEmpty = 0;
            var FieldsNotEmpty = 0;
            var count = 0

            group.each(function () {

                var _val = $(this).val()
                var length = _val.length

                if (length > 0) {
                    FieldsNotEmpty++;
                }
                else {
                    FieldsEmpty++;
                }
                count++;
            })

            var isValid = (FieldsNotEmpty >=1)
            //recursively execute
            group.each(function (index) {
                if (CheckReccursion === index) {
                    CheckReccursion++;
                    $(this).parsley().validate();
                    CheckReccursion = 0;
                }
            })
            return isValid;
        }
    });

$(function () {
    var ok=false;
    var notice =$('#notice');

    $('#form1').parsley().on('form:validated', function(formInstance) {
        ok = formInstance.isValid({force: true});
    })
    .on('form:submit', function() {
        if(!ok){
            notice.html('Please fill at least 1 field');
            return false;
        }
        else{
            notice.html('okay');
            return false;//change to true to submit form here

        }
    });
});

查看这个小提琴https://jsfiddle.net/xcoL5Lur/6/